'use strict';

// Selecting elements
const score0El = document.querySelector('#score--0');
const score1El = document.getElementById('score--1');
const diceEl = document.querySelector('.dice');
const btnNew = document.querySelector('.btn--new'); //更新按键
const btnRoll = document.querySelector('.btn--roll'); //丢骰子按键
const btnHold = document.querySelector('.btn--hold'); //记录分数按键

const current0 = document.getElementById('current--0');
const current1 = document.getElementById('current--1');
const player0 = document.querySelector('.player--0');
const player1 = document.querySelector('.player--1');
const name0 = document.getElementById('name--0');
const name1 = document.getElementById('name--1');

let scores, currentScore, activePlayer;

const init = function () {
  scores = [0, 0];
  currentScore = 0;
  activePlayer = 0;

  score0El.textContent = 0;
  score1El.textContent = 0;
  current0.textContent = 0;
  current1.textContent = 0;

  diceEl.classList.add('hidden');
  player0.classList.remove('player--winner');
  player1.classList.remove('player--winner');
  player0.classList.add('player--active');
  player1.classList.remove('player--active');

  name0.textContent = 'player 1';
  name1.textContent = 'player 2';
};
init();
//更换活跃玩家
const whoplay = function () {
  currentScore = 0;
  document.getElementById(`current--${activePlayer}`).textContent =
    currentScore;
  activePlayer = activePlayer === 0 ? 1 : 0;
  player0.classList.toggle('player--active');
  player1.classList.toggle('player--active');
};

//丢骰子功能
btnRoll.addEventListener('click', function () {
  let number = Math.trunc(Math.random() * 6) + 1;
  console.log(number);
  //显示骰子
  diceEl.classList.remove('hidden');
  diceEl.src = `dice-${number}.png`;
  //更新计数板

  //骰到1
  if (number !== 1) {
    currentScore += number;
    document.getElementById(`current--${activePlayer}`).textContent =
      currentScore;
  } else {
    //先清零 后换人
    whoplay();
  }
});
//保存成绩按键
btnHold.addEventListener('click', function () {
  scores[activePlayer] += currentScore;
  document.getElementById(`score--${activePlayer}`).textContent =
    scores[activePlayer];

  //超过100分胜利
  if (scores[activePlayer] >= 100) {
    document.getElementById(`name--${activePlayer}`).textContent = 'Winner';
    diceEl.classList.add('hidden');

    document
      .querySelector(`.player--${activePlayer}`)
      .classList.add('player--winner');
    document
      .querySelector(`.player--${activePlayer}`)
      .classList.remove('player--active');
    //将current 框清0
    document.getElementById(`current--${activePlayer}`).textContent = '0';
  } else {
    //保存后换人
    whoplay();
  }
});
//重置game按钮
btnNew.addEventListener('click', init);
